package finalgame.GUI;

import org.lwjgl.input.Keyboard;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.opengl.Texture;

import finalgame.Game;
import finalgame.Util;
import finalgame.Engine.Battle;
import finalgame.Graphics.Location;
import finalgame.Graphics.RenderEngine;
import finalgame.Graphics.RenderObj;

public abstract class TextMenu implements RenderObj {
	protected int sel_index = 0;
	protected String[] strings;
	protected String currentTitle;
	protected Location baseLoc;
	
	/**
	 * Get size of array (assuming that there are no null elements before last actual element)
	 * @return logical size of array (or at least "Safe" size)
	 */
	private<T> int getSize(T[] array) { 
		for(int i = 0; i < array.length; i++)
			if(array[i] == null) return i;
		return array.length;
	}
	
	/**
	 * Get the width of a string
	 * @param s
	 * @return
	 */
	private float getWidth(String s) {
		return Game.game.getFont("default.lg").getWidth(s);
	}
	
	public void render() {
		Location tempLoc = new Location(baseLoc);
		// Get the render font
		UnicodeFont font = Game.game.getFont("default.lg");
		// Draw title
		font.drawString((float) tempLoc.x(), (float) tempLoc.y(), currentTitle);
		for(int i = 0; i < strings.length; i++) { // Draw each of the "buttons
			if(strings[i] == null) return;
			tempLoc.y(tempLoc.y() + Game.game.getFontHeight("default.lg") + 5);
			// If button is selected, draw "arrow" indicating so
			if(i == sel_index) font.drawString((float) tempLoc.x() - getWidth("-") - 5, (float) tempLoc.y(), "-");
			font.drawString((float) tempLoc.x(), (float) tempLoc.y(), strings[i]);
		}
	}
	
	public abstract void select();
	
	public abstract void exit();
	
	/**
	 * Update the menu
	 */
	protected int key_down = -30;
	public void update() {
		if(key_down < 0) {
			key_down++;
			return;
		}
		// If a key is down, set a flag indicating so
		if(Keyboard.isKeyDown(Keyboard.KEY_UP)) key_down = Keyboard.KEY_UP;
		else if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) key_down = Keyboard.KEY_DOWN;
		else if (Keyboard.isKeyDown(Keyboard.KEY_A)) key_down = Keyboard.KEY_A;
		else if (Keyboard.isKeyDown(Keyboard.KEY_B)) key_down = Keyboard.KEY_B;
		else {
			// When that key is lifted, perform corresponding action
			// Move selected index up
			if(key_down == Keyboard.KEY_UP) sel_index += sel_index > 0 ? -1 : 0;
			// Move selected index down
			else if(key_down == Keyboard.KEY_DOWN) sel_index += (sel_index + 1) < getSize(strings) ? 1 : 0;
			else if(key_down == Keyboard.KEY_A) select(); // Select current option
			else if(key_down == Keyboard.KEY_B) exit(); // Exit current "menu"
			if(key_down != -1) key_down = 0;
		}
		sel_index = Util.bound(sel_index, 0, getSize(strings) - 1);
	}
}
